#include "include/shortcutinput.h"

#include <QStyle>
#include <QStylePainter>
#include <QStyleOptionButton>
#include <QPaintEvent>
#include <QKeyEvent>
#include <QDebug>
#include <QAction>
#include <QPalette>

namespace
{

	const char* NoneText = "None";
	const char* InputText = "Input...";

} //private namespace



ShortcutInput::ShortcutInput(QWidget *parent) :
	QWidget(parent), _sequenceDefined(false)
{
	this->setFocusPolicy(Qt::StrongFocus);
	//this->setAttribute(Qt::WA_KeyCompression);
}


QKeySequence ShortcutInput::sequence() const
{
	//return _sequenceDefined ? _sequence : QKeySequence();
	return _sequence;
}


void ShortcutInput::setSequence(const QKeySequence &value)
{
	if (_sequence == value)
		return;

	_sequenceDefined = !value.isEmpty();
	_sequence = value;

	_text = _sequence.toString();
	update();
}


void ShortcutInput::resetSequence()
{
	setSequence(QKeySequence());
}


void ShortcutInput::keyPressEvent(QKeyEvent * evt)
{
	_sequenceDefined = !evt->text().isEmpty();
	QKeySequence seq = _sequenceDefined ? QKeySequence((int)evt->modifiers() + evt->key()) : QKeySequence(evt->modifiers());
	_text = _sequenceDefined ? seq.toString() : seq.toString() + "...";
	update();

	if (_sequenceDefined)
	{
		_sequence = seq;
		emit sequenceChanged();
	}
}

void ShortcutInput::keyReleaseEvent(QKeyEvent *)
{
	if (!_sequenceDefined)
		_text = "";

	update();
}


void ShortcutInput::focusInEvent(QFocusEvent *)
{
	_text = "";
	update();
}


void ShortcutInput::focusOutEvent(QFocusEvent *)
{
	update();
}


void ShortcutInput::paintEvent(QPaintEvent *)
{
	QStylePainter painter(this);

	QStyleOptionButton option;
	option.initFrom(this);

	if (_text.isEmpty())
		option.text = hasFocus() ? tr(InputText) : tr(NoneText);
	else
		option.text = _text;

	option.state = hasFocus() ? QStyle::State_Sunken : QStyle::State_Raised;

	if (isEnabled())
		option.state |= QStyle::State_Enabled;

	painter.drawControl(QStyle::CE_PushButton, option);
}
